const express = require("express")
const app = express()
const { ObjectId } = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
// getparam中间件
/*	chunk:
    如果是get 要传 req.url
    如果是post 要传 path +? +chunk
    param:
          要获取参数的key

    必须调用next，否则请求将被挂起
*/
const getparam = (req, res, next) => {
    if (req.method == "POST") {
        let chunk = ""
        req.on("data", (data) => {
            chunk += data.toString()
        })
        req.on("end", () => {
            let url = "http://127.0.0.1:8080" + req.url + "?" + chunk
            let myurl = new URL(url)
            req.searchparam = myurl.searchParams
            next()
        })
    } else if (req.method == "GET") {
        let url = "http://127.0.0.1:8080" + req.url
        let myurl = new URL(url)
        req.searchparam = myurl.searchParams

        next()
    }
}

const infolog = (req, res, next) => {

    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();
    let timeStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    console.log("[" + timeStr + "]" + ":" + "请求地址:" + req.url.split("?")[0] + "\n");

    next()
}

app.use(getparam)
app.use(infolog)
var url = "mongodb://localhost:27017";
var db
MongoClient.connect(url, function (err, client) {
    if (err) throw err;
    db = client.db("lqsq");
});

app.get("/api/articleList", (req, res) => {
    db.collection("article").find().project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
        if (err) throw err
        res.json(resu)
    });
})

app.get("/api/authorsList", (req, res) => {
    //前提数据库中至少存在4条数据，否则将死循环
    db.collection("user").find().project({ _id: 1, userName: 1, headImg: 1, desc: 1 }).toArray((err, resu) => {
        if (err) throw err
        //使用set 存储不重复的数据取到随机的四个数据
        var four = new Set();
        while (four.size < 4) {
            four.add(Math.floor(Math.random() * resu.length))
        }
        var arr = []
        four.forEach((e) => {
            arr.push(resu[e])
        })
        var obj = {
            "status": "ok",
            "data": arr
        }
        res.json(obj)
    });
})

app.get("/api/classifyArticleList", (req, res) => {
    var classify = req.searchparam.get("classify")
    db.collection("article").find({ "classify": classify }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
        if (err) throw err
        res.json(resu)
    });
})

app.get("/api/findArticleDetails", (req, res) => {
    var id = req.searchparam.get("id")
    db.collection("article").find({ "_id": new ObjectId(id) }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 ,time:1}).toArray((err, resu) => {
        if (err) throw err
        res.json(resu)
    });
})
app.post("/api/userLogin", (req, res) => {
    var username = req.searchparam.get("userName")
    var password = req.searchparam.get("userPassword")
    db.collection("user").find({ "userName": username, "userPassword": password }).project({ _id: 1, userName: 1, headImg: 1 }).toArray((err, resu) => {
        if (err) throw err
        var obj = {
            "status": "ok",
            "data": resu[0]
        }
        res.json(obj)
    });
})
app.post("/api/addUser", (req, res) => {
    var username = req.searchparam.get("userName")
    var password = req.searchparam.get("userPassword")
    var desc = req.searchparam.get("desc")
    db.collection("user").find({ "userName": username }).project({ _id: 1, userName: 1, headImg: 1 }).toArray((err, resu) => {
        if (err) throw err
        //没有找到即存在 再进行添加用户
        if (resu[0] == undefined) {
            var createTime = new Date()
            var randomimg ="headimg"+ Math.floor((Math.random()+1))*12+".png"

            db.collection("user").insertOne({ "userName": username, "userPassword": password, "desc": desc, "headImg": randomimg, "createTime": createTime }, (err, resu) => {
                if (err) throw err
                let obj = {
                    "_id": resu.insertedId,
                    "userName": username,
                    "createTime": createTime,
                    "headImg": randomimg,
                    "desc": desc,
                }
                res.json(obj)
            })
        } else {
            let obj = {
                "status": "ok"
            }
            res.json(obj)
        }
    })
})

app.get("/api/myArticleList", (req, res) => {
    var userId = req.searchparam.get("userId")

    db.collection("article").find({ "authorId": userId }).project({ _id: 1, title: 1, desc: 1, author: 1, authorId: 1, classify: 1, content: 1 }).toArray((err, resu) => {
        if (err) throw err
        res.json(resu)
    });
})

app.post("/api/addArticle", (req, res) => {
    var title = req.searchparam.get("title")
    var content = req.searchparam.get("content")
    var desc = req.searchparam.get("desc")
    var author = req.searchparam.get("author")
    var authorId = req.searchparam.get("authorId")
    var classify = req.searchparam.get("classify")
    db.collection("article").insertOne({ "title": title, "content": content, "desc": desc, "author": author, "authorId": authorId, "classify": classify, "time": new Date() }, (err, resu) => {
        if (err) throw err
        res.json(true)
    })
})

app.post("/api/updateIdArticle", (req, res) => {
    var _id = req.searchparam.get("_id")
    var title = req.searchparam.get("title")
    var content = req.searchparam.get("content")
    var desc = req.searchparam.get("desc")
    var author = req.searchparam.get("author")
    var authorId = req.searchparam.get("authorId")
    var classify = req.searchparam.get("classify")
    var time = new Date()
    db.collection("article").updateOne({ "_id": new ObjectId(_id) }, { $set: { "title": title, "content": content, "desc": desc, "author": author, "authorId": authorId, "classify": classify, "time": time } }, (err, resu) => {
        if (err) throw err
        let obj = {
            "title": title,
            "content": content,
            "desc": desc,
            "author": author,
            "authorId": authorId,
            "classify": classify,
            "time": time,
            "__v": 0,
            "_id": _id
        }
        res.json(obj)
    })
})
app.get("/api/deleteArticle", (req, res) => {
    var id = req.searchparam.get("id")
    db.collection("article").deleteOne({ "_id": new ObjectId(id) }, (err, resu) => {
        if (err) throw err
        if (resu.deletedCount >= 1) {
            res.json(resu.acknowledged)
        } else {
            res.json(false)
        }
    })
})

app.listen(3001, () => {
    console.log("server start...")
})